package com.gjt.clientSocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Logger;

public class IntegenClient {
    private static int DEFAUPT_PORT = 1920;
    private static Logger logger = Logger.getLogger("IntegenLog");

    public static void main(String[] args) {
        if (args.length == 0) {
            logger.info("没有输入主机");
            return;
        }

        int port;
        try {
            port = Integer.parseInt(args[1]);
        } catch (RuntimeException e) {
            logger.info("端口输入错误， 使用默认端口 ： " + DEFAUPT_PORT);
            port = DEFAUPT_PORT;
        }
        try {
            SocketChannel socketChannel = SocketChannel.open();
            if (!socketChannel.isOpen()) {
                logger.warning("通道没有打开 ");
                return;
            }

            socketChannel.connect(new InetSocketAddress("152.136.138.218", port));
            if (!socketChannel.isConnected()) {
                logger.warning("通道没有连接");
                return;
            }

            // 创建直接字节缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4);
            // 转换成 视图缓冲区
            IntBuffer intBuffer = byteBuffer.asIntBuffer();

            for (int exception = 0; ; exception++) {
                socketChannel.read(byteBuffer);
                int actual = intBuffer.get();
                byteBuffer.clear();
                intBuffer.rewind();

                if(actual != exception){
                    System.out.println("异常：" + actual + "  实际：" + exception);
                    break;
                }
                System.out.println(actual);
            }

        } catch (IOException e) {

        }
    }
}
